package com.kaci.springbootormlite.controller;

import com.j256.ormlite.dao.Dao;
import com.kaci.springbootormlite.component.DatabaseHelper;
import com.kaci.springbootormlite.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private DatabaseHelper databaseHelper;

    @PostMapping
    public User createUser(@RequestBody User user) throws SQLException {
        databaseHelper.getUserDao().create(user);
        return user;
    }

    @GetMapping
    public Integer getAllUsers()  {
        Dao<User, Integer> userDao = databaseHelper.getUserDao();
        // 模拟并发查询
        for (int i = 0; i < 10; i++) {
            DatabaseHelper.executorService.submit(() -> {
                // 查询所有用户
                List<User> users = userDao.queryForAll();
                System.out.println("Current users: " + users.size());
                return users.size();
            });
        }
         return null;
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable int id) throws SQLException {
        return databaseHelper.getUserDao().queryForId(id);
    }

    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable int id) throws SQLException {
        databaseHelper.getUserDao().deleteById(id);
    }
}